# 标准内置对象—RegExp
# 创建
正则表达式:定义字符串的组成规则
字面量(使用多)
var reg = /正则表达式/;利用 RegExp 对象,需要注意字符串中的转义字符
var reg = new RegExp("正则表达式");
# 使用
test(str):验证指定的字符串是否符合正则定义的规范,返回 boolean 值exec(str):返回匹配到的第一个的内容。只有给正则后添加g并多次调用即可多次匹配!var str = "where when what"; var reg = /wha/; var reg2 = /wh/g; console.log(reg.exec(str)); // ["wha", index: 11, input: "where when what", groups: undefined] console.log(reg2.exec(str)); // ["wh", index: 0, input: "where when what", groups: undefined] console.log(reg2.exec(str)); // ["wh", index: 6, input: "where when what", groups: undefined] console.log(reg2.exec(str)); // ["wh", index: 11, input: "where when what", groups: undefined] console.log(reg2.exec(str)); // null console.log(reg.test(str)); // true
# 规则
# 单个字符
如 a、ab(a或b)、a~zA~Z0~9_。特殊符号代表特殊含义的单个字符:
.:单个任意字符\d:单个数字字符0~9\w:单个单词字符a~zA~Z0~9_\s:单个如空格、换行符
# 量词符号
?:表示出现0次或1次*:表示出现0次或多次+:出现1次或多次{m,n}:表示 m<= 数量 <= n- m如果缺省:
{,n}最多n次 - n如果缺省:
{m,}最少m次
- m如果缺省:
# 开始结束符号
^:开始$:结束